<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>待办事项管理</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />
    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .task-transition {
          transition: all 0.3s ease-in-out;
        }
        .fade-in {
          animation: fadeIn 0.3s ease-in;
        }
        .fade-out {
          animation: fadeOut 0.3s ease-out;
        }
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(-10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        @keyframes fadeOut {
          from {
            opacity: 1;
            transform: translateY(0);
          }
          to {
            opacity: 0;
            transform: translateY(10px);
          }
        }
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen flex flex-col items-center py-8">
    <div class="w-full max-w-md px-4">
      <h1 class="text-4xl font-bold text-indigo-600 text-center mb-2">
        待办事项
      </h1>
      <p class="text-gray-500 text-center mb-8">简单高效地管理你的任务</p>

      <!-- 添加待办区域 -->
      <div class="flex mb-6">
        <input
          type="text"
          id="taskInput"
          placeholder="添加新的待办事项..."
          class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-indigo-500"
        />
        <button
          id="addTaskBtn"
          class="bg-indigo-600 text-white px-6 py-2 rounded-r-md hover:bg-indigo-700 transition-colors"
        >
          <i class="fa fa-plus mr-1"></i> 添加
        </button>
      </div>

      <!-- 过滤按钮 -->
      <div class="flex mb-6 space-x-2">
        <button
          id="filterAll"
          class="px-4 py-1 rounded-full border border-indigo-500 text-indigo-600 font-medium"
        >
          全部
        </button>
        <button
          id="filterActive"
          class="px-4 py-1 rounded-full border border-gray-300 text-gray-600 hover:border-gray-400 transition-colors"
        >
          未完成
        </button>
        <button
          id="filterCompleted"
          class="px-4 py-1 rounded-full border border-gray-300 text-gray-600 hover:border-gray-400 transition-colors"
        >
          已完成
        </button>
      </div>

      <!-- 待办列表 -->
      <ul id="taskList" class="space-y-2">
        <!-- 任务项将通过 JS 动态生成 -->
      </ul>

      <!-- 统计信息 -->
      <div class="mt-8 py-3 bg-white rounded-md text-center text-gray-600">
        <p id="taskStats">0 个未完成，0 个总计</p>
      </div>
    </div>
    <script>
      // 待办事项类
      class Todo {
        constructor(id, text, completed = false) {
          this.id = id;
          this.text = text;
          this.completed = completed;
        }
      }
      // 待办事项管理器
      class TodoManager {
        constructor() {
          this.todos = [];
          this.currentFilter = 'all'; // 默认显示全部
          this.loadFromStorage(); // 页面加载时从本地存储读取数据
          this.renderTasks(); // 渲染初始任务
          this.bindEvents(); // 绑定事件
        }

        // 从本地存储加载数据
        loadFromStorage() {
          const storedTodos = localStorage.getItem('todos');
          if (storedTodos) {
            this.todos = JSON.parse(storedTodos).map(todo => 
              new Todo(todo.id, todo.text, todo.completed)
            );
          }
        }

        // 保存数据到本地存储
        saveToStorage() {
          localStorage.setItem('todos', JSON.stringify(this.todos));
        }

        // 添加新待办事项 - 修改为添加到数组开头
        addTodo(text) {
          if (!text.trim()) return;
          const newTodo = new Todo(Date.now(), text);
          // 将新任务添加到数组开头而不是末尾
          this.todos.unshift(newTodo);
          this.saveToStorage();
          this.renderTasks(this.currentFilter);
          
          // 清空输入框并聚焦
          const input = document.getElementById('taskInput');
          input.value = '';
          input.focus();
        }

        // 切换待办事项的完成状态
        toggleTodo(id) {
          const todo = this.todos.find(t => t.id === id);
          if (todo) {
            // 为切换状态添加动画效果
            const taskItem = document.querySelector(`li [data-id="${id}"]`).closest('li');
            taskItem.classList.add('task-transition');
            
            todo.completed = !todo.completed;
            this.saveToStorage();
            this.renderTasks(this.currentFilter);
          }
        }

        // 删除待办事项
        deleteTodo(id) {
          // 找到要删除的元素并添加淡出动画
          const taskItem = document.querySelector(`li [data-id="${id}"]`).closest('li');
          taskItem.classList.add('fade-out');
          
          // 等待动画完成后再删除
          setTimeout(() => {
            this.todos = this.todos.filter(t => t.id !== id);
            this.saveToStorage();
            this.renderTasks(this.currentFilter);
          }, 300);
        }

        // 过滤待办事项（全部/未完成/已完成）
        filterTodos(status) {
          if (status === 'active') {
            return this.todos.filter(t => !t.completed);
          } else if (status === 'completed') {
            return this.todos.filter(t => t.completed);
          }
          return this.todos; // 全部
        }

        // 渲染待办事项列表
        renderTasks(filterStatus = 'all') {
          this.currentFilter = filterStatus;
          const taskList = document.getElementById('taskList');
          taskList.innerHTML = '';

          const filteredTodos = this.filterTodos(filterStatus);

          if (filteredTodos.length === 0) {
            // 显示空状态提示
            const emptyItem = document.createElement('li');
            emptyItem.className = 'bg-white p-4 rounded-md text-center text-gray-500';
            emptyItem.textContent = filterStatus === 'active' 
              ? '没有未完成的任务，真棒！' 
              : filterStatus === 'completed'
                ? '没有已完成的任务'
                : '还没有添加任何任务';
            taskList.appendChild(emptyItem);
          } else {
            filteredTodos.forEach(todo => {
              const taskItem = document.createElement('li');
              taskItem.className = 'bg-white p-3 rounded-md task-transition fade-in flex items-center justify-between';

              // 完成状态样式
              const checkboxClass = todo.completed
                ? 'bg-indigo-600 text-white'
                : 'border border-gray-300';
              const textClass = todo.completed
                ? 'text-gray-400 line-through'
                : 'text-gray-800';

              taskItem.innerHTML = `
                <div class="flex items-center">
                  <input
                    type="checkbox"
                    class="h-5 w-5 rounded ${checkboxClass} focus:ring-indigo-500 transition-colors"
                    ${todo.completed ? 'checked' : ''}
                    data-id="${todo.id}"
                  >
                  <span class="ml-3 ${textClass} transition-colors" data-id="${todo.id}">${todo.text}</span>
                </div>
                <button class="text-gray-400 hover:text-red-500 transition-colors p-1" data-id="${todo.id}">
                  <i class="fa fa-trash"></i>
                </button>
              `;

              taskList.appendChild(taskItem);
            });
          }

          // 更新统计信息
          const activeCount = this.todos.filter(t => !t.completed).length;
          const totalCount = this.todos.length;
          document.getElementById('taskStats').textContent = `${activeCount} 个未完成，${totalCount} 个总计`;
        }

        // 绑定事件
        bindEvents() {
          // 添加任务（按钮点击）
          document.getElementById('addTaskBtn').addEventListener('click', () => {
            const input = document.getElementById('taskInput');
            this.addTodo(input.value);
          });

          // 添加任务（回车提交）
          document.getElementById('taskInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
              const input = document.getElementById('taskInput');
              this.addTodo(input.value);
            }
          });

          // 切换完成状态
          document.getElementById('taskList').addEventListener('change', (e) => {
            if (e.target.type === 'checkbox') {
              const id = parseInt(e.target.dataset.id);
              this.toggleTodo(id);
            }
          });

          // 删除任务
          document.getElementById('taskList').addEventListener('click', (e) => {
            if (e.target.closest('button')) {
              const id = parseInt(e.target.closest('button').dataset.id);
              this.deleteTodo(id);
            }
          });

          // 过滤任务（全部）
          document.getElementById('filterAll').addEventListener('click', () => {
            this.updateFilterButtons('all');
            this.renderTasks('all');
          });

          // 过滤任务（未完成）
          document.getElementById('filterActive').addEventListener('click', () => {
            this.updateFilterButtons('active');
            this.renderTasks('active');
          });

          // 过滤任务（已完成）
          document.getElementById('filterCompleted').addEventListener('click', () => {
            this.updateFilterButtons('completed');
            this.renderTasks('completed');
          });
        }

        // 更新过滤按钮的样式
        updateFilterButtons(activeFilter) {
          const filters = ['all', 'active', 'completed'];
          filters.forEach(filter => {
            const btn = document.getElementById(`filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`);
            if (filter === activeFilter) {
              btn.className = 'px-4 py-1 rounded-full border border-indigo-500 text-indigo-600 font-medium';
            } else {
              btn.className = 'px-4 py-1 rounded-full border border-gray-300 text-gray-600 hover:border-gray-400 transition-colors';
            }
          });
        }
      }
      // 页面加载时初始化
      document.addEventListener('DOMContentLoaded', () => {
        new TodoManager();
        // 初始聚焦到输入框
        document.getElementById('taskInput').focus();
      });
    </script>
  </body>
</html>